/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistence;

import entityBeans.Locality;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entityBeans.Localityelement;
import java.util.ArrayList;
import java.util.List;
import persistence.exceptions.NonexistentEntityException;

/**
 *
 * @author allankv
 */
public class LocalityJpaController {

    public LocalityJpaController() {
        emf = Persistence.createEntityManagerFactory("bdd-javaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Locality save(Locality locality) {
        Locality aux = findLocality(locality.getLocality());
        if(aux==null)
            return create(locality);
        else
            return aux;
    }

    public Locality create(Locality locality) {
        Locality r = null;
        if (locality.getLocalityelementList() == null) {
            locality.setLocalityelementList(new ArrayList<Localityelement>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Localityelement> attachedLocalityelementList = new ArrayList<Localityelement>();
            for (Localityelement localityelementListLocalityelementToAttach : locality.getLocalityelementList()) {
                localityelementListLocalityelementToAttach = em.getReference(localityelementListLocalityelementToAttach.getClass(), localityelementListLocalityelementToAttach.getIdlocalityelement());
                attachedLocalityelementList.add(localityelementListLocalityelementToAttach);
            }
            locality.setLocalityelementList(attachedLocalityelementList);
            r = em.merge(locality);
            for (Localityelement localityelementListLocalityelement : locality.getLocalityelementList()) {
                Locality oldLocalityOfLocalityelementListLocalityelement = localityelementListLocalityelement.getLocality();
                localityelementListLocalityelement.setLocality(locality);
                localityelementListLocalityelement = em.merge(localityelementListLocalityelement);
                if (oldLocalityOfLocalityelementListLocalityelement != null) {
                    oldLocalityOfLocalityelementListLocalityelement.getLocalityelementList().remove(localityelementListLocalityelement);
                    oldLocalityOfLocalityelementListLocalityelement = em.merge(oldLocalityOfLocalityelementListLocalityelement);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return r;
    }

    public void edit(Locality locality) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Locality persistentLocality = em.find(Locality.class, locality.getIdlocality());
            List<Localityelement> localityelementListOld = persistentLocality.getLocalityelementList();
            List<Localityelement> localityelementListNew = locality.getLocalityelementList();
            List<Localityelement> attachedLocalityelementListNew = new ArrayList<Localityelement>();
            for (Localityelement localityelementListNewLocalityelementToAttach : localityelementListNew) {
                localityelementListNewLocalityelementToAttach = em.getReference(localityelementListNewLocalityelementToAttach.getClass(), localityelementListNewLocalityelementToAttach.getIdlocalityelement());
                attachedLocalityelementListNew.add(localityelementListNewLocalityelementToAttach);
            }
            localityelementListNew = attachedLocalityelementListNew;
            locality.setLocalityelementList(localityelementListNew);
            locality = em.merge(locality);
            for (Localityelement localityelementListOldLocalityelement : localityelementListOld) {
                if (!localityelementListNew.contains(localityelementListOldLocalityelement)) {
                    localityelementListOldLocalityelement.setLocality(null);
                    localityelementListOldLocalityelement = em.merge(localityelementListOldLocalityelement);
                }
            }
            for (Localityelement localityelementListNewLocalityelement : localityelementListNew) {
                if (!localityelementListOld.contains(localityelementListNewLocalityelement)) {
                    Locality oldLocalityOfLocalityelementListNewLocalityelement = localityelementListNewLocalityelement.getLocality();
                    localityelementListNewLocalityelement.setLocality(locality);
                    localityelementListNewLocalityelement = em.merge(localityelementListNewLocalityelement);
                    if (oldLocalityOfLocalityelementListNewLocalityelement != null && !oldLocalityOfLocalityelementListNewLocalityelement.equals(locality)) {
                        oldLocalityOfLocalityelementListNewLocalityelement.getLocalityelementList().remove(localityelementListNewLocalityelement);
                        oldLocalityOfLocalityelementListNewLocalityelement = em.merge(oldLocalityOfLocalityelementListNewLocalityelement);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = locality.getIdlocality();
                if (findLocality(id) == null) {
                    throw new NonexistentEntityException("The locality with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Locality locality;
            try {
                locality = em.getReference(Locality.class, id);
                locality.getIdlocality();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The locality with id " + id + " no longer exists.", enfe);
            }
            List<Localityelement> localityelementList = locality.getLocalityelementList();
            for (Localityelement localityelementListLocalityelement : localityelementList) {
                localityelementListLocalityelement.setLocality(null);
                localityelementListLocalityelement = em.merge(localityelementListLocalityelement);
            }
            em.remove(locality);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Locality> findLocalityEntities() {
        return findLocalityEntities(true, -1, -1);
    }

    public List<Locality> findLocalityEntities(int maxResults, int firstResult) {
        return findLocalityEntities(false, maxResults, firstResult);
    }

    private List<Locality> findLocalityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Locality.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Locality findLocality(String q) {
        Query query= getEntityManager().createNamedQuery("Locality.findByLocality");
        query.setParameter("locality",q);

        return query.getResultList().isEmpty()?null:(Locality)query.getResultList().get(0);
    }

    public Locality findLocality(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Locality.class, id);
        } finally {
            em.close();
        }
    }


    public int getLocalityCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Locality> rt = cq.from(Locality.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
